package com.hsjk.szwj.module.pay.controller.app.transfer;

import cn.hutool.core.util.ObjectUtil;
import com.hsjk.szwj.framework.common.exception.ServiceException;
import com.hsjk.szwj.framework.common.exception.enums.GlobalErrorCodeConstants;
import com.hsjk.szwj.module.pay.controller.PayApiController;
import com.hsjk.szwj.module.pay.controller.app.transfer.vo.QueryTransferOrderReqVO;
import com.hsjk.szwj.module.pay.controller.app.transfer.vo.QueryTransferOrderRespVO;
import com.hsjk.szwj.module.pay.dal.dataobject.CommonPayResult;
import com.hsjk.szwj.module.pay.dal.dataobject.order.TransferOrderDO;
import com.hsjk.szwj.module.pay.dal.dataobject.system.MchInfoDO;
import com.hsjk.szwj.module.pay.service.ConfigContextQueryService;
import com.hsjk.szwj.module.pay.service.IMchAppService;
import com.hsjk.szwj.module.pay.service.IMchInfoService;
import com.hsjk.szwj.module.pay.service.TransferOrderService;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author chenjiawei
 * @desc
 * @Date 2023/08/25 18:13
 **/
@Tag(name = "应用端 - 转账查询相关接口")
@RestController
@RequestMapping("/transfer")
@Validated
@Slf4j
public class QueryTransferOrderController extends PayApiController {

    @Resource
    private TransferOrderService transferOrderService;
    @Resource
    private ConfigContextQueryService configContextQueryService;
    @Resource
    private IMchInfoService mchInfoService;
    @Resource
    private IMchAppService mchAppService;

    /**
     * 查单接口
     **/
    @RequestMapping("/api/transfer/query")
    public CommonPayResult queryTransferOrder() {

        //获取参数 & 验签
        QueryTransferOrderReqVO rq = getRQByWithMchSign(QueryTransferOrderReqVO.class);

        if (ObjectUtil.isNull(rq.getMchOrderId()) && ObjectUtil.isNull(rq.getTransferId())) {
            throw new ServiceException(GlobalErrorCodeConstants.BAD_REQUEST.getCode(),
                    "mchOrderNo 和 transferId不能同时为空");
        }
        MchInfoDO mchInfoDO = mchInfoService.getMchInfoById(rq.getMchId());
        TransferOrderDO refundOrder =
                transferOrderService.queryMchOrder(mchInfoDO.getId(), rq.getMchOrderId(),
                        rq.getTransferId());
        if (refundOrder == null) {
            throw new ServiceException(GlobalErrorCodeConstants.BAD_REQUEST.getCode(),
                    "订单不存在");
        }

        QueryTransferOrderRespVO bizRes = QueryTransferOrderRespVO.buildByRecord(refundOrder);
        return CommonPayResult.okWithSign(bizRes,
                configContextQueryService.queryMchApp(rq.getMchId(),
                        rq.getAppId()).getAppSecret());
    }
}
